package com.ruoyi.system.service.impl;
import java.util.*;

import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONArray;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.CrmDataStatus;
import com.ruoyi.common.enums.CrmIsDeleteType;
import com.ruoyi.common.enums.CrmJobStatus;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.SysAddressDTO;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IBsAreaService;
import com.ruoyi.system.service.ICrmUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.service.ICrmJobService;

/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author ruoyi
 * @date 2020-10-12
 */
@Service
public class CrmJobServiceImpl implements ICrmJobService 
{
    @Autowired
    private CrmJobMapper crmJobMapper;
    @Autowired
    private CJobLogMapper cJobLogMapper;

    @Autowired
    private CJobCustomerMapper cJobCustomerMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private CrmUserMapper crmCustomerMapper;

    @Autowired
    private ICrmJobService crmJobService;
    @Autowired
    private ICrmUserService crmCustomerService;
    @Autowired
    private IBsAreaService bsAreaServiceImpl;
    /**
     * 查询【请填写功能名称】
     * 
     * @param id 【请填写功能名称】ID
     * @return 【请填写功能名称】
     */
    @Override
    public CrmJob selectCrmJobById(Long id)
    {
        return crmJobMapper.selectCrmJobById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     * 
     * @param crmJob 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<CrmJob> selectCrmJobList(CrmJob crmJob)
    {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        crmJob.setCreateUser(userId);
        crmJob.setStatus(CrmDataStatus.OK.getCode());
        crmJob.setIsDelete(CrmIsDeleteType.OK.getCode());
        List<CrmJob> crmJobs = crmJobMapper.selectCrmJobList(crmJob);
        return crmJobs;
    }

    /**
     * 新增【请填写功能名称】
     * 
     * @param crmJob 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertCrmJob(CrmJob crmJob)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId=loginUser.getUser().getUserId();
        crmJob.setCreateUser(userId);
        crmJob.setCreateTime(new Date());
        crmJob.setUpdateTime(new Date());
        crmJob.setUpdateUser(userId);
        crmJob.setIsDelete(CrmIsDeleteType.OK.getCode());
        crmJob.setStatus(CrmDataStatus.OK.getCode());
        crmJob.setJobStatus(CrmJobStatus.NOSTART.getCode());
        BsArea areaByLgla = bsAreaServiceImpl.getAreaByLgla(crmJob.getJobLalg());
        SysAddressDTO addressCodeByArea = bsAreaServiceImpl.getAddressCodeByArea(areaByLgla);
        if(addressCodeByArea!=null) {
            crmJob.setJobProvinceCode(addressCodeByArea.getBsProvince()==null?null:addressCodeByArea.getBsProvince().getProvinceCode());
            crmJob.setJobCityCode(addressCodeByArea.getBsCity()==null?null:addressCodeByArea.getBsCity().getCityCode());
            crmJob.setJobAreaCode(addressCodeByArea.getBsArea()==null?null:addressCodeByArea.getBsArea().getAreaCode());
        }
        if(crmJob.getTipsTime() !=null){
            Date tipTimeByType = DateUtils.getTipTimeByType(crmJob.getJobStartTime(), crmJob.getTipsTime());
            crmJob.setJobStartTipsTime(tipTimeByType);
        }
        //添加事件
        int i1 = crmJobMapper.insertCrmJob(crmJob);
        //添加 客户 与 事件的关联
        //获取 客户id数组
        String jobCustomer = crmJob.getJobCustomer();
        if(jobCustomer!=null && !"".equals(jobCustomer)){
            List<Long> cusIdList=new ArrayList<>();
            cusIdList = JSONArray.parseArray(jobCustomer, Long.class);
            for (Long cusId: cusIdList
            ) {
                CJobCustomer cJobCustomer = new CJobCustomer();
                cJobCustomer.setJobId(crmJob.getId());
                cJobCustomer.setCusId(cusId);
                cJobCustomer.setStatus(CrmDataStatus.OK.getCode());
                cJobCustomer.setIsDelete(CrmIsDeleteType.OK.getCode());
                cJobCustomer.setCreateTime(new Date());
                cJobCustomer.setUpdateTime(new Date());
                cJobCustomerMapper.insertCJobCustomer(cJobCustomer);
            }
        }
        return i1;
    }

    /**
     * 修改【请填写功能名称】
     * 
     * @param crmJob 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateCrmJob(CrmJob crmJob)
    {
        CrmJob tmp = crmJobMapper.selectCrmJobById(crmJob.getId());
        tmp.setTipsTime(crmJob.getTipsTime());
        if(crmJob.getTipsTime() != null){
            crmJob.setJobStartTipsTime(DateUtils.getTipTimeByType(crmJob.getJobStartTime(),crmJob.getTipsTime()));
        }
        if(crmJob.getTipsTime() == null){
            long oldtime = tmp.getJobStartTime().getTime();
            long newtime = crmJob.getJobStartTime().getTime();
            Date jobStartTipsTime = tmp.getJobStartTipsTime();
            long fintime = jobStartTipsTime.getTime() + (newtime - oldtime);
            jobStartTipsTime.setTime(fintime);
            crmJob.setJobStartTipsTime(jobStartTipsTime);
        }
        BsArea areaByLgla = bsAreaServiceImpl.getAreaByLgla(crmJob.getJobLalg());
        SysAddressDTO addressCodeByArea = bsAreaServiceImpl.getAddressCodeByArea(areaByLgla);
        if(addressCodeByArea!=null){
            crmJob.setJobProvinceCode(addressCodeByArea.getBsProvince()==null?"":addressCodeByArea.getBsProvince().getProvinceCode());
            crmJob.setJobCityCode(addressCodeByArea.getBsCity()==null?"":addressCodeByArea.getBsCity().getCityCode());
            crmJob.setJobAreaCode(addressCodeByArea.getBsArea()==null?"":addressCodeByArea.getBsArea().getAreaCode());

        }
        return crmJobMapper.updateCrmJob(crmJob);
    }

    /**
     * 批量删除【请填写功能名称】
     * 
     * @param ids 需要删除的【请填写功能名称】ID
     * @return 结果
     */
    @Override
    public int deleteCrmJobByIds(Long[] ids)
    {
        return crmJobMapper.deleteCrmJobByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     * 
     * @param id 【请填写功能名称】ID
     * @return 结果
     */
    @Override
    public int deleteCrmJobById(Long id)
    {
        return crmJobMapper.deleteCrmJobById(id);
    }

    public int deleteCrmJobAndLogById(Long id){
        cJobLogMapper.deleteCJobLogByJobId(id);
        return crmJobMapper.deleteCrmJobById(id);

    }

    /**
     * 根据客户 查询关联的任务
     * @param id
     * @return
     */
    @Override
    public List<CrmJob> getJobByCustomer(Long id) {
        //根据客户id查询 任务 客户关联表
        CJobCustomer cJobCustomer =new CJobCustomer();
        cJobCustomer.setCusId(id);
        cJobCustomer.setStatus(CrmDataStatus.OK.getCode());
        cJobCustomer.setIsDelete(CrmIsDeleteType.OK.getCode());
        List<CJobCustomer> cJobCustomersById = cJobCustomerMapper.selectCJobCustomerList(cJobCustomer);
        //根据客户id查 相关事件
        List<Long> jobIds=new ArrayList<>();
        for (CJobCustomer cJCus : cJobCustomersById
             ) {
            jobIds.add(cJCus.getJobId());
        }
        if(jobIds == null || jobIds.size() < 1){
            return null;
        }
        List<CrmJob> crmJobs = crmJobMapper.selectCrmJobByIds(jobIds);
        //查询所有客户  转为map   id-客户
        CrmUser tmp=new CrmUser();
        tmp.setStatus(CrmDataStatus.OK.getCode());
        tmp.setIsDelete(CrmIsDeleteType.OK.getCode());
        List<CrmUser> crmCustomers = crmCustomerMapper.selectCrmUserList(tmp);
        final Map<Long, CrmUser> crmCustomerMap = crmCustomers.stream().collect(Collectors.toMap(CrmUser::getId, crmCustomer -> crmCustomer, (k1, k2) -> k1));
        CJobCustomer cjcParam =new CJobCustomer();
        cjcParam.setStatus(CrmDataStatus.OK.getCode());
        cjcParam.setIsDelete(CrmIsDeleteType.OK.getCode());
        //获取任务关联的 客户
        List<CJobCustomer> cJobCustomersAll = cJobCustomerMapper.selectCJobCustomerList(cjcParam);
        CrmUser cusParam=new CrmUser();
        cusParam.setIsDelete(CrmIsDeleteType.OK.getCode());
        cusParam.setStatus(CrmDataStatus.OK.getCode());
        List<CrmUser> crmCustomersAll = crmCustomerMapper.selectCrmUserList(cusParam);
        Map<Long, CrmUser> crmCustomersAllMap = crmCustomersAll.stream().collect(Collectors.toMap(CrmUser::getId, crmCustomer -> crmCustomer, (k1, k2) -> k1));
        for (CJobCustomer cJobCustomerTmp : cJobCustomersAll
             ) {
            cJobCustomerTmp.setCrmCustomer(crmCustomersAllMap.get(cJobCustomerTmp.getCusId()));
        }
        //  任务 关联的 客户信息
        Map<Long, List<CJobCustomer>> jobIdCusList = cJobCustomersAll.stream().collect(Collectors.groupingBy(CJobCustomer::getJobId));
        for (CrmJob tmpJ  : crmJobs
             ) {
            List<CJobCustomer> cJobCustomers = jobIdCusList.get(tmpJ.getId());
            List<CrmUser> collect = cJobCustomers.stream().map(CJobCustomer::getCrmCustomer).collect(Collectors.toList());
            tmpJ.setCustomerList(collect);
        }
        return crmJobs;
    }

    @Override
    public int deleteCustomerAboutJob(Long customerId) {
        List<CrmJob> jobByCustomer = getJobByCustomer(customerId);
        List<Long> jobIds=new ArrayList<>();
        for (CrmJob crmJob : jobByCustomer
             ) {
            jobIds.add(crmJob.getId());
        }
        //客户相关任务移除
        int i = crmJobMapper.deleteCrmJobByIdsForUpdate(jobIds);
        return i;
    }

    /**
     *今天的代办
     * @return
     */
    @Override
    public List<CrmJob> selectCrmJobByToday(String searchValue,Long userId){
        return crmJobMapper.selectCrmJobByToday(searchValue,userId);
    }

    @Override
    public List<CrmJob> selectCrmJobByTodayNotice(Long userId){
        return crmJobMapper.selectCrmJobByTodayNotice(userId);
    }

    public List<CrmJob> selectCrmJobByMinuteNotice(Long userId,Integer n){
        return crmJobMapper.selectCrmJobByMinuteNotice(userId,n);

    }


    /**
     *明天及以后
     * @return
     */
    public List<CrmJob> selectCrmJobByNextDay(String searchValue,Long userId){
        return crmJobMapper.selectCrmJobByNextDay(searchValue,userId);
    }

    /**
     *历史
     * @return
     */
    public List<CrmJob> selectCrmJobByPreDay(String searchValue,Long userId){
        return crmJobMapper.selectCrmJobByPreDay(searchValue,userId);
    }


    public List<CrmJob>  selectCrmJobByDay(Date date, Long userId){
        return crmJobMapper.selectCrmJobByDay(date,userId);
    }

}
